package com.abc.service.impl;

import com.abc.entity.User;
import com.abc.entity.UserLoginDTO;
import com.abc.mapper.UserMapper;
import com.abc.service.IUserService;
import com.abc.service.ex.GlobalException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import com.abc.service.ex.InsertException;
import com.abc.service.ex.UsernameDuplicateException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User user) throws UsernameDuplicateException, InsertException {
        User user1 = userMapper.findByUsername(user.getUsername());
        if(user1!=null){
            throw new UsernameDuplicateException("用户名已存在,注册失败");
        }
        int k = userMapper.insertUser(user);
        if(k==0){
            throw new UsernameDuplicateException("注册失败");
        }
    }

    public User findByUsername(String username){
        return userMapper.findByUsername(username);
    }
    @Override
    public void login(UserLoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        // 根据用户名查询用户信息
        System.out.println(username);
        User user = userMapper.selectByUsername(username);
        System.out.println(user);
        if (user != null) {
            // shiro登录认证
            UsernamePasswordToken token = new UsernamePasswordToken(username, loginDTO.getPassword());
            System.out.println(token);
            Subject subject = SecurityUtils.getSubject();
            try {
                subject.login(token);
            }catch(AuthenticationException e){
                throw new GlobalException("用户名或密码错误~");
            }
            // 设置session失效时间：永不超时
            subject.getSession().setTimeout(-1001);
        } else {
            throw new GlobalException("用户名不存在~");
        }
    }
}
